package com.zuipin.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zuipin.entity.MemberLevel;
import com.zuipin.entity.RedPacket;
import com.zuipin.entity.SendNoQuantityLog;
import com.zuipin.entity.shoppingCart.CartParam;
import com.zuipin.entity.shoppingCart.RuleSet;
import com.zuipin.entity.shoppingCart.RuleType;
import com.zuipin.entity.shoppingCart.ShoppingCart;
import com.zuipin.enums.RedPackStatus;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.RedPacketMapper;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.service.IMemberLevelService;
import com.zuipin.service.IRedPacketService;
import com.zuipin.service.IRuleSetService;
import com.zuipin.service.ISendNoQuantityLogService;
import com.zuipin.service.IShoppingCartService;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.Convert;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;
import com.zuipin.util.RedisUtils;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.CheckRuleSetParam;
import com.zuipin.vo.CheckRuleSetResult;
import com.zuipin.vo.RedPacketDetailVo;
import com.zuipin.vo.RedPacketShowVo;
import com.zuipin.vo.RedPacketVo;
import com.zuipin.vo.SearchCanUseVo;
import com.zuipin.vo.SendMemberVo;
import com.zuipin.vo.SendRedPacketResult;

/**
 * @ClassName: RedPackServiceImpl
 * @author wuyicheng
 * @time 2017年3月27日下午4:04:09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RedPackServiceImpl implements IRedPacketService {
	@Resource
	private RedPacketMapper				redPacketMapper;
	
	@Resource
	private IShoppingCartService		shoppingCartService;
	
	@Resource
	private IMemberLevelService			memberLevelService;
	
	@Resource
	private IMemberAccountService		memberAccountService;
	
	@Resource
	private IRuleSetService				ruleSetService;
	
	@Resource
	private ISendNoQuantityLogService	sendNoQuantityLogService;
	
	@Resource
	private RedisUtils					redisUtils;
	
	private static Logger				log	= LoggerFactory.getLogger(RedPackServiceImpl.class);
	
	/**
	 * @Title: findById
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:23:47
	 * @param id
	 * @return
	 * @throws
	 */
	@Override
	public RedPacket findById(Long id) {
		return redPacketMapper.findById(id);
	}
	
	/**
	 * @Title: insert
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:23:47
	 * @param redPacket
	 * @throws
	 */
	@Override
	public void insert(RedPacket redPacket) {
		redPacket.setCreateTime(DateUtils.getCurrentDateTime());
		redPacket.setUpdateTime(DateUtils.getCurrentDateTime());
		redPacket.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
		redPacketMapper.insert(redPacket);
	}
	
	/**
	 * @Title: update
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:23:47
	 * @param redPacket
	 * @throws
	 */
	@Override
	public void update(RedPacket redPacket) {
		redPacket.setUpdateTime(DateUtils.getCurrentDateTime());
		redPacketMapper.update(redPacket);
	}
	
	/** 
	 * 
	 * 
	 * @Title: findList 
	 * @author: wuyicheng
	 * @date: 2017年4月24日下午5:03:40 
	 * @param redPacket
	 * @param page
	 * @return
	 * @throws 
	 */
	@Override
	public List<RedPacket> findListByPage(RedPacket redPacket, Pagination page) {
		return redPacketMapper.findListByPage(redPacket, page);
	}
	
	/** 
	 *
	 * @Title: findList 
	 * @author: wuyicheng
	 * @date: 2017年4月25日上午12:38:30 
	 * @param redPacket
	 * @return
	 * @throws 
	 */
	@Override
	public List<RedPacket> findList(RedPacket redPacket) {
		return redPacketMapper.findList(redPacket);
	}
	
	/** 
	 * 根据会员ID和系统ID查询可用红包数量
	 * 
	 * @Title: countRedPacket 
	 * @author: wuyicheng
	 * @date: 2017年4月27日下午6:26:48 
	 * @param memberId
	 * @param sysId
	 * @return
	 * @throws 
	 */
	@Override
	public long countRedPacket(Long memberId, Long sysId) {
		RedPacket redPacket = new RedPacket();
		redPacket.setMemberId(memberId);
		redPacket.setSysId(sysId);
		redPacket.setStatus(RedPackStatus.UNUSED);
		redPacket.setEndTime(DateUtils.getCurrentDateTime());
		return redPacketMapper.countRedPacket(redPacket);
	}
	
	/**
	 * @throws CustomException 
	 * 根据优惠券代码和密码激活红包
	 * 
	 * @throws ParseException  
	 *
	 * @Title: doActivateByCodeAndPwd 
	 * @author: wuyicheng
	 * @date: 2017年5月3日上午9:33:12 
	 * @param memberId 会员ID
	 * @param sysId 系统ID
	 * @param activateCode 优惠券代码
	 * @param activatePassword 优惠券密码
	 * @return
	 * @throws 
	 */
	@Override
	public Result<Map<String, Object>> doActivateByCodeAndPwd(Long memberId, Long sysId, String activateCode, String activatePassword) throws ParseException, CustomException {
		Result<Map<String, Object>> result = new Result<>();
		RedPacket redPacket = findByCodeAndPwd(activateCode, activatePassword, sysId);
		if (redPacket != null) {
			boolean isLateFlag = isLate(redPacket);
			if (!isLateFlag) {
				// 如果当前红包已经绑定会员ID不再派发
				if (redPacket.getMemberId() == null) {
					redPacket.setMemberId(memberId);
					update(redPacket);
					result.setErrorCode(ErrorCode.SUCCESS);
					result.setData(null);
				} else {
					result.setErrorCode(ErrorCode.ELSE);
					// 优惠劵已经在其他地方激活
					result.setMessage("Coupons have been activated elsewhere");
					result.setData(null);
				}
			} else {
				result.setErrorCode(ErrorCode.ELSE);
				// 优惠劵已过期
				result.setMessage("The coupon has expired");
				result.setData(null);
			}
		} else {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("Code is error or password is error");
			result.setData(null);
		}
		
		return result;
	}
	
	/**
	 * 红包是否过期
	 * 
	 * @throws ParseException  
	 *
	 * @Title: isLate 
	 * @author: wuyicheng
	 * @date: 2017年5月3日上午11:37:39 
	 * @param redPacket
	 * @return
	 * @return: boolean true 过期 false 没过期
	 * @throws 
	 */
	private boolean isLate(RedPacket redPacket) throws ParseException {
		long startDate = DateUtils.parseFullTime(redPacket.getStartTime()).getTime();
		long endDate = DateUtils.parseFullTime(redPacket.getEndTime()).getTime();
		long currentDate = DateUtils.getDate().getTime();
		// 判断当前时间再有效期内
		if (startDate <= currentDate && endDate >= currentDate) {
			return false;
		}
		return true;
	}
	
	/** 
	 * 根据优惠券代码和密码查询红包
	 * 
	 * @Title: findByCodeAndPwd 
	 * @author: wuyicheng
	 * @date: 2017年5月3日上午9:34:13 
	 * @param activateCode
	 * @param activatePassword
	 * @param sysId
	 * @return
	 * @return: RedPacket
	 * @throws 
	 */
	private RedPacket findByCodeAndPwd(String activateCode, String activatePassword, Long sysId) {
		RedPacket redPacket = new RedPacket();
		redPacket.setActivateCode(activateCode);
		redPacket.setActivatePassword(activatePassword);
		redPacket.setSysId(sysId);
		return redPacketMapper.findByRedPacket(redPacket);
	}
	
	/**
	 * @throws CustomException 
	 * 根据优惠劵序列号激活红包
	 * 
	 * @throws ParseException  
	 *
	 * @Title: doActivateBySerialNumber 
	 * @author: wuyicheng
	 * @date: 2017年5月3日上午11:10:19 
	 * @param memberId
	 * @param sysId
	 * @param serialNumber
	 * @return
	 * @throws 
	 */
	@Override
	public Result<Map<String, Object>> doActivateBySerialNumber(Long memberId, Long sysId, String serialNumber) throws ParseException, CustomException {
		Result<Map<String, Object>> result = new Result<>();
		
		RedPacket redPacket = this.findBySerialNumberAndSysId(serialNumber, sysId);
		
		// 红包不存在
		if (redPacket == null) {
			result.setErrorCode(ErrorCode.RED_PACKET_NULL);
			return result;
		}
		
		// 如果当前红包已经绑定会员ID不再派发
		if (redPacket.getMemberId() != null) {
			result.setErrorCode(ErrorCode.REDPACKET_ACTIVATED);
			return result;
		}
		
		RuleSet ruleSet = ruleSetService.findRuleById(redPacket.getCreateRuleId());
		String currentTime = DateUtils.getCurrentDateTime();
		
		CheckRuleSetParam checkRuleSetParam = new CheckRuleSetParam(memberId, sysId, ruleSet, CheckRuleSetParam.GET_0);
		checkRuleSetParam.setCurrentTime(currentTime);
		CheckRuleSetResult checkRuleSetResult = ruleSetService.checkRuleSet(checkRuleSetParam);
		// 验证成功派发红包
		// 是否符合领取规则
		if (!(CheckRuleSetResult.YES_1.equals(checkRuleSetResult.getIsCanGet()))) {
			// 检验规则不符合
			log.info("不符合红包领取规则，红包ID为：{}，会员ID为：{},错误信息：{}", redPacket.getId(), memberId, checkRuleSetResult.getErrorCode());
			result.setErrorCode(checkRuleSetResult.getErrorCode());
			return result;
		}
		
		// 如果是有效天数，更新开始结束时间
		this.modRedPacktByValidDay(redPacket, ruleSet, currentTime);
		
		// 判断是否过期
		boolean isOverdue = ruleSetService.isOverdue(redPacket.getStartTime(), redPacket.getEndTime(), currentTime);
		
		// 未过期，可派发
		if (isOverdue) {
			
			// 优惠劵已过期
			result.setErrorCode(ErrorCode.RULE_ARE_OUTDATED);
			return result;
			
		}
		
		// 构建修改的红包信息
		this.buildModRedPack(memberId, sysId, null, currentTime, RedPackStatus.UNUSED, redPacket);
		
		this.update(redPacket);
		
		this.updateRuleSetUseNum(ruleSet, 1, currentTime);
		
		// 激活成功返回红包ID
		Map<String, Object> map = new HashMap<>();
		map.put("redPacketId", redPacket.getId());
		result.setData(map);
		result.setErrorCode(ErrorCode.SUCCESS);
		
		return result;
	}
	
	/**
	 * 更新红包规则使用数量
	 *
	 * @Title: updateRuleSetUseNum 
	 * @author: wuyicheng
	 * @date: 2017年7月28日下午9:45:36 
	 * @param ruleSet 红包规则
	 * @param nums 使用数量
	 * @param currentTime 当前时间
	 * @return: void
	 * @throws
	 */
	private void updateRuleSetUseNum(RuleSet ruleSet, int nums, String currentTime) {
		if (ruleSet != null) {
			int useNum = (ruleSet.getUseNum() == null) ? 0 : ruleSet.getUseNum();
			ruleSet.setUseNum(useNum + nums);
			ruleSet.setUpdateTime(currentTime);
			ruleSetService.updateById(ruleSet);
		}
	}
	
	/** 
	 *
	 * @Title: findBySerialNumberAndSysId 
	 * @author: wuyicheng
	 * @date: 2017年7月12日上午8:45:52 
	 * @param serialNumber
	 * @param sysId
	 * @return
	 * @return: RedPacket
	 * @throws 
	 */
	private RedPacket findBySerialNumberAndSysId(String serialNumber, Long sysId) {
		RedPacket redPacket = new RedPacket();
		redPacket.setRedPacketKey(serialNumber);
		redPacket.setSysId(sysId);
		return redPacketMapper.findByRedPacket(redPacket);
	}
	
	/**
	 * 根据规则ID激活红包
	 *
	 * @Title: doActivateByRuleId 
	 * @author: wuyicheng
	 * @date: 2017年7月11日下午6:12:18 
	 * @param memberId
	 * @param sysId
	 * @param ruleId
	 * @return
	 * @throws ParseException
	 * @throws CustomException
	 * @throws
	 */
	@Override
	public Result<Map<String, Object>> doActivateByRuleId(Long memberId, Long sysId, Long ruleId) throws ParseException, CustomException {
		Result<Map<String, Object>> result = new Result<>();
		
		RuleSet ruleSet = ruleSetService.findRuleById(ruleId);
		
		String currentTime = DateUtils.getCurrentDateTime();// 当前系统时间
		CheckRuleSetParam checkRuleSetParam = new CheckRuleSetParam(memberId, sysId, ruleSet, CheckRuleSetParam.GET_0);
		checkRuleSetParam.setCurrentTime(currentTime);
		
		// 检查规则结果
		CheckRuleSetResult checkRuleSetResult = ruleSetService.checkRuleSet(checkRuleSetParam);
		if (checkRuleSetResult == null) {
			result.setErrorCode(ErrorCode.EXCEPTION);
			return result;
		}
		// 是否符合领取规则
		if (!(CheckRuleSetResult.YES_1.equals(checkRuleSetResult.getIsCanGet()))) {
			// 检验规则不符合
			log.info("不符合红包领取规则，规则ID为：{}，会员ID为：{},错误信息：{}", ruleSet.getId(), memberId, checkRuleSetResult.getErrorCode());
			result.setErrorCode(checkRuleSetResult.getErrorCode());
			return result;
		}
		
		// 查询规则对应的红包
		List<RedPacket> redPacketList = this.searchCanGetRedPacket(ruleSet, sysId, currentTime, 1);
		// 没有可领取的红包
		if (redPacketList == null || redPacketList.size() <= 0) {
			result.setErrorCode(ErrorCode.RULE_NO_RED_PACKET);
			return result;
		}
		
		RedPacket redPacket = redPacketList.get(0);
		
		// 如果是有效天数，更新开始结束时间
		this.modRedPacktByValidDay(redPacket, ruleSet, currentTime);
		
		// 构建修改的红包信息
		this.buildModRedPack(memberId, sysId, null, currentTime, RedPackStatus.UNUSED, redPacket);
		
		this.update(redPacket);
		
		// 修改使用数量
		this.updateRuleSetUseNum(ruleSet, 1, currentTime);
		
		result.setErrorCode(ErrorCode.SUCCESS);
		
		return result;
		
	}
	
	/**
	 * 是否过期
	 *
	 * @Title: isOverdue 
	 * @author: wuyicheng
	 * @date: 2017年7月11日下午4:57:56 
	 * @param startTime
	 * @param endTime
	 * @param currentTime
	 * @return
	 * @throws ParseException
	 * @return: boolean
	 * @throws
	 */
	private boolean isOverdue(String startTime, String endTime, String currentTime) throws ParseException {
		long startDate = DateUtils.parseFullTime(startTime).getTime();
		long endDate = DateUtils.parseFullTime(endTime).getTime();
		long currentDate = DateUtils.parseFullTime(currentTime).getTime();
		// 判断当前时间再有效期内
		if (startDate <= currentDate && endDate >= currentDate) {
			return false;
		}
		return true;
		
	}
	
	/**
	 * 查询可用红包
	 *
	 * @Title: getCanUseRedpacket 
	 * @author: wuyicheng
	 * @date: 2017年6月21日上午11:21:22 
	 * @param searchCanUseVo
	 * @return
	 * @throws CustomException
	 * @return: List<RedPacketVo>
	 * @throws
	 */
	@Override
	public List<RedPacketVo> getCanUseRedpacket(SearchCanUseVo searchCanUseVo) throws CustomException {
		List<ShoppingCart> shoppingCartList = shoppingCartService.createVirtualShoppingCart(searchCanUseVo.getOrderDetailVos(), searchCanUseVo.getMemberId(),
				searchCanUseVo.getSysId());
		
		if (shoppingCartList == null || shoppingCartList.size() < 1) {
			return null;
		}
		
		CartParam cartParam = new CartParam();
		cartParam.setBuyerId(searchCanUseVo.getMemberId());
		cartParam.setSysId(searchCanUseVo.getSysId());
		cartParam.setDevice(searchCanUseVo.getDevice());
		// cartParam.setProTotalAmount(searchCanUseVo.getProductSum());
		MemberLevel memberLevel = memberLevelService.findByMemberIdAndSysId(searchCanUseVo.getMemberId(), searchCanUseVo.getSysId());
		shoppingCartService.shoppingCartDetail(cartParam, shoppingCartList, memberLevel);
		// 查询红包列表
		List<RedPacketVo> list = shoppingCartService.getCartRedPacket(shoppingCartList, cartParam);
		return list;
	}
	
	/**
	 * @throws CustomException 
	 * @throws ParseException  
	 * 后台派发红包
	 * 
	 * @Title: toSendRedPacket 
	 * @author: wuyicheng
	 * @date: 2017年7月10日上午11:53:47 
	 * @param sysUserId
	 * @param sysId
	 * @param ruleSetId
	 * @param isMemberLevel
	 * @param acceptor
	 * @return
	 * @throws 
	 */
	@Override
	public Result<SendRedPacketResult> toSendRedPacket(Long sysUserId, Long sysId, Long ruleSetId, Short isMemberLevel, String acceptor) throws ParseException, CustomException {
		
		if (redisUtils.exists(ConstantsUtil.SEND_REDPACKET_FLAG)) {
			throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(), "有进程正在努力派发红包中，请稍等重试");
		}
		
		Result<SendRedPacketResult> result = new Result<>(ErrorCode.SUCCESS);
		String currentTime = DateUtils.getCurrentDateTime();// 获取系统当前时间
		RuleSet ruleSet = ruleSetService.findRuleById(ruleSetId);
		
		// 检查规则
		CheckRuleSetParam checkRuleSetParam = new CheckRuleSetParam(null, sysId, ruleSet, CheckRuleSetParam.GET_0);
		checkRuleSetParam.setCurrentTime(currentTime);
		CheckRuleSetResult checkRuleSetResult = ruleSetService.checkRuleSet(checkRuleSetParam);
		
		// 是否符合领取规则
		if (!(CheckRuleSetResult.YES_1.equals(checkRuleSetResult.getIsCanGet()))) {
			// 检验规则不符合
			log.info("不符合红包领取规则，红包规则ID为：{}，后台操作人员ID为：{},错误信息：{}", ruleSetId, sysUserId, checkRuleSetResult.getErrorCode());
			result.setErrorCode(checkRuleSetResult.getErrorCode());
			return result;
		}
		
		// ==================================================================
		// 派发信息
		SendRedPacketResult sendRedPacketResult = new SendRedPacketResult();
		long canGetNums = ruleSet.getCreateNum() - ruleSet.getUseNum();// 规则可派发红包数量
		
		Map<String, Object> searchMap = new HashMap<>();
		searchMap.put("sysId", sysId);
		List<String> acceptorList = Arrays.asList(acceptor.split(ConstantsUtil.COMMA));
		List<String> searchAcceptorList = new ArrayList<>();
		// 去重复
		Map<String, String> phoneAndLevelMap = new HashMap<>();
		for (String phoneLevel : acceptorList) {
			if (StringUtil.isNotBlank(phoneLevel) && phoneAndLevelMap.get(phoneLevel) == null) {
				phoneAndLevelMap.put(phoneLevel, "-");
				searchAcceptorList.add(phoneLevel);
			}
		}
		
		if (SendRedPacketResult.SEND_MEMBER_LEVEL_YES_1 == isMemberLevel) {
			searchMap.put("memberLevels", searchAcceptorList);// 按照等级派发
		} else {
			searchMap.put("phones", searchAcceptorList);// 按照手机号派发
		}
		
		// 查询全部会员
		List<Map<String, Object>> sendMemberList = memberAccountService.searchSendMember(searchMap);
		// 没有可以派发的会员
		if (sendMemberList == null || sendMemberList.size() <= 0) {
			sendRedPacketResult = this.buildSendResult(isMemberLevel, phoneAndLevelMap, 0, new StringBuffer(""), 0);
			result.setData(sendRedPacketResult);
			result.setErrorCode(ErrorCode.SUCCESS);
			return result;
		}
		
		// 会员数量小于可派发数量，查询对应数量红包
		if (sendMemberList.size() <= canGetNums) {
			canGetNums = sendMemberList.size();
		}
		sendRedPacketResult = this.doSend(ruleSet, sendMemberList, phoneAndLevelMap, canGetNums, currentTime, sysUserId, isMemberLevel, sysId);
		result.setData(sendRedPacketResult);
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	/**
	 * 派发红包
	 *
	 * @Title: doSend 
	 * @author: wuyicheng
	 * @date: 2017年7月31日下午5:05:06 
	 * @param ruleSet 红包规则
	 * @param sendMemberList 领取红包会员
	 * @param phoneAndLevelMap 派发的手机号
	 * @param canGetNums 领取的数量
	 * @param currentTime 系统当前时间
	 * @param sysUserId 当前系统操作人
	 * @param isMemberLevel 是否等级派发
	 * @param sysId 系统ID
	 * @return
	 * @throws ParseException
	 * @return: SendRedPacketResult
	 * @throws
	 */
	private SendRedPacketResult doSend(RuleSet ruleSet, List<Map<String, Object>> sendMemberList, Map<String, String> phoneAndLevelMap, long canGetNums, String currentTime,
			Long sysUserId, Short isMemberLevel, Long sysId) throws ParseException {
		// 查询限制的会员
		Map<Long, Integer> limitMemberMap = null;
		if (RuleSet.YES.equals(ruleSet.getIsLimitGetNum())) {
			limitMemberMap = this.getLimitMemberMap(sysId, ruleSet.getId(), ruleSet.getLimitGetNum());
		}
		// 查询可用红包
		List<RedPacket> canGetRedPacketList = this.searchCanGetRedPacket(ruleSet, sysId, currentTime, new Long(canGetNums).intValue());
		List<RedPacket> waitUpdateRedPacks = new ArrayList<>();
		
		StringBuffer failPhone = new StringBuffer("");// 失败手机号
		long successNums = 0L;// 成功数量
		long failNums = 0L;// 失败数量
		for (int i = 0; i < sendMemberList.size(); i++) {
			
			Map<String, Object> map = sendMemberList.get(i);
			SendMemberVo sendMemberVo = new SendMemberVo();
			try {
				PropertyUtils.copyProperties(sendMemberVo, map);
			} catch (IllegalAccessException e) {
				log.error("派发红包转换异常", e);
			} catch (InvocationTargetException e) {
				log.error("派发红包转换异常", e);
			} catch (NoSuchMethodException e) {
				log.error("派发红包转换异常", e);
			}
			
			// 按手机派发，移除已派发手机号
			if (SendRedPacketResult.SEND_MEMBER_LEVEL_NO_0 == isMemberLevel) {
				if (StringUtil.isNotBlank(sendMemberVo.getMobilePhone()) && phoneAndLevelMap.get(sendMemberVo.getMobilePhone()) != null) {
					phoneAndLevelMap.remove(sendMemberVo.getMobilePhone());
				}
			}
			
			// 是否满足领取条件
			boolean isCanUse = this.checkRuleIsCanUse(ruleSet, sendMemberVo, limitMemberMap, failNums, failPhone, successNums, canGetNums);
			// 还有可派发红包
			if (!isCanUse || canGetRedPacketList == null || canGetRedPacketList.size() <= 0 || successNums >= canGetRedPacketList.size()) {
				
				failNums++;
				if (StringUtil.isNotBlank(sendMemberVo.getMobilePhone())) {
					failPhone.append(sendMemberVo.getMobilePhone()).append(",");
				}
				continue;
			}
			RedPacket redPacket = canGetRedPacketList.get(new Long(successNums).intValue());
			// 如果是有效天数，更新开始结束时间
			this.modRedPacktByValidDay(redPacket, ruleSet, currentTime);
			// 构建修改的红包
			this.buildModRedPack(sendMemberVo.getMemberId(), sysId, sysUserId, currentTime, RedPackStatus.UNUSED, redPacket);
			waitUpdateRedPacks.add(redPacket);
			successNums++;
			
		}
		// 批量更新红包
		if (waitUpdateRedPacks != null && waitUpdateRedPacks.size() > 0) {
			this.updateRuleSetUseNum(ruleSet, waitUpdateRedPacks.size(), currentTime);
			this.batchUpdateByThread(waitUpdateRedPacks);
		}
		SendRedPacketResult sendRedPacketResult = this.buildSendResult(isMemberLevel, phoneAndLevelMap, failNums, failPhone, successNums);
		return sendRedPacketResult;
	}
	
	/** 
	 * 构建派送结果
	 * 
	 * @Title: buildSendResult 
	 * @author: wuyicheng
	 * @date: 2017年7月31日下午4:15:35 
	 * @param isMemberLevel 是否按照会员等级
	 * @param phoneAndLevelMap 输入的手机号
	 * @param failNums 失败数量
	 * @param failPhone 失败手机号
	 * @param successNums 成功数量
	 * @return
	 * @return: SendRedPacketResult
	 * @throws 
	 */
	private SendRedPacketResult buildSendResult(Short isMemberLevel, Map<String, String> phoneAndLevelMap, long failNums, StringBuffer failPhone, long successNums) {
		SendRedPacketResult sendRedPacketResult = new SendRedPacketResult();
		// 按手机派发，且手机号有数据库存在的
		if (SendRedPacketResult.SEND_MEMBER_LEVEL_NO_0 == isMemberLevel && phoneAndLevelMap != null && phoneAndLevelMap.size() > 0) {
			for (String phone : phoneAndLevelMap.keySet()) {
				failPhone.append(phone).append(",");
				failNums++;
			}
		}
		
		// 如果错误手机不空,去掉最后一个逗号
		if (failPhone != null && StringUtil.isNotBlank(failPhone.toString())) {
			sendRedPacketResult.setFailPhone(failPhone.toString().substring(0, failPhone.toString().length() - 1));
		} else {
			sendRedPacketResult.setFailPhone("");
		}
		sendRedPacketResult.setSuccessNums(successNums);
		sendRedPacketResult.setFailNums(failNums);
		return sendRedPacketResult;
	}
	
	/** 
	 * 获取领取次数超出限制的会员
	 * 
	 * @Title: getLimitMemberMap 
	 * @author: wuyicheng
	 * @date: 2017年7月31日下午4:11:46 
	 * @param sysId 系统ID
	 * @param ruleSetId 规则ID
	 * @param joinNums 限制参与次数
	 * @return
	 * @return: Map<Long,Integer>
	 * @throws 
	 */
	private Map<Long, Integer> getLimitMemberMap(Long sysId, Long ruleSetId, Integer joinNums) {
		List<Map<String, Object>> getLimitMemberList = new ArrayList<>();
		Map<Long, Integer> limitMemberMap = new HashMap<>();
		if (joinNums != null) {
			getLimitMemberList = redPacketMapper.searchGetNumByMemberId(sysId, ruleSetId, joinNums);
			if (getLimitMemberList != null && getLimitMemberList.size() > 0) {
				for (Map<String, Object> map : getLimitMemberList) {
					limitMemberMap.put(Convert.toLong(map.get("memberId")), joinNums);
				}
			}
		}
		return limitMemberMap;
	}
	
	/** 
	 * 验证是否符合红包领取规则
	 * 
	 * @Title: checkRule 
	 * @author: wuyicheng
	 * @date: 2017年7月29日上午11:27:40 
	 * @param ruleSet
	 * @param sendMemberVo
	 * @param limitMemberMap
	 * @param failNums
	 * @param failPhone
	 * @param successNums
	 * @param canGetNums
	 * @return
	 * @return: boolean
	 * @throws 
	 */
	private boolean checkRuleIsCanUse(RuleSet ruleSet, SendMemberVo sendMemberVo, Map<Long, Integer> limitMemberMap, long failNums, StringBuffer failPhone, long successNums,
			long canGetNums) {
		boolean isTrue = true;
		// 可派发数量小于等于派发成功数量，停止派发，记录剩余会员手机号
		if (canGetNums <= successNums) {
			isTrue = false;
		}
		
		// 手机号空，邮箱空，派发失败
		if (StringUtil.isBlank(sendMemberVo.getMobilePhone()) && StringUtil.isBlank(sendMemberVo.getEmail())) {
			isTrue = false;
		}
		
		// 手机不是空，会员ID空
		if (StringUtil.isNotBlank(sendMemberVo.getMobilePhone()) && sendMemberVo.getMemberId() == null) {
			isTrue = false;
		}
		
		// 会员ID空
		if (sendMemberVo.getMemberId() == null) {
			isTrue = false;
		}
		
		// 是否限购领取次数
		if (limitMemberMap != null && limitMemberMap.get(sendMemberVo.getMemberId()) != null) {
			isTrue = false;
		}
		
		// 限购等级
		if (StringUtil.isNotBlank(ruleSet.getLimitMemberLevel())
				&& !StringUtil.isContains(sendMemberVo.getMemberLevelId().toString(), ruleSet.getLimitMemberLevel(), ConstantsUtil.COMMA)) {
			isTrue = false;
		}
		return isTrue;
	}
	
	/** 
	 * 开启线程批量更新红包
	 * 
	 * @Title: batchUpdateByThread 
	 * @author: wuyicheng
	 * @date: 2017年7月28日下午4:44:26 
	 * @param waitUpdateRedPacks
	 * @return: void
	 * @throws 
	 */
	private void batchUpdateByThread(List<RedPacket> waitUpdateRedPacks) {
		// 速度太慢 开个线程
		new Thread(new Runnable() {
			public void run() {
				long startTime = DateUtils.getDate().getTime();
				log.info("开始线程，红包派发开始.................");
				redisUtils.set(ConstantsUtil.SEND_REDPACKET_FLAG, "true", 60 * 60 * 1);
				try {
					
					int x = 1000;
					for (int i = 0; i < waitUpdateRedPacks.size(); i = i + x) {
						if ((i + x) > waitUpdateRedPacks.size()) {
							redPacketMapper.batchUpdate(waitUpdateRedPacks.subList(i, waitUpdateRedPacks.size()));
						} else {
							redPacketMapper.batchUpdate(waitUpdateRedPacks.subList(i, i + x));
						}
					}
				} catch (Exception e) {
					log.error("红包派发异常", e);
				} finally {
					long endTime = DateUtils.getDate().getTime();
					log.info("红包派发结束................时间{}", (endTime - startTime));
					if (redisUtils.exists(ConstantsUtil.SEND_REDPACKET_FLAG)) {
						redisUtils.del(ConstantsUtil.SEND_REDPACKET_FLAG);
					}
				}
				
			}
		}).start();
		
	}
	
	/**
	 * 构建将派发的红包信息
	 *
	 * @Title: buildModRedPack 
	 * @author: wuyicheng
	 * @date: 2017年7月12日下午6:06:14 
	 * @param memberId
	 * @param sysId
	 * @param sysUserId
	 * @param currentTime
	 * @param redPackStatus
	 * @param redPacket
	 * @return: void
	 * @throws
	 */
	private void buildModRedPack(Long memberId, Long sysId, Long sysUserId, String currentTime, RedPackStatus redPackStatus, RedPacket redPacket) {
		redPacket.setMemberId(memberId);
		redPacket.setSysId(sysId);
		redPacket.setUpdateTime(currentTime);
		redPacket.setUpdateId(sysUserId);
		redPacket.setPayoutId(sysUserId);
		redPacket.setPayoutTime(currentTime);
		redPacket.setDrawMemberId(memberId);
		redPacket.setDrawMemberTime(currentTime);
		redPacket.setStatus(redPackStatus);
	}
	
	/** 
	 * 批量更新红包信息
	 * 
	 * @Title: batchUpdate 
	 * @author: wuyicheng
	 * @date: 2017年7月12日下午4:58:47 
	 * @param waitUpdateRedPacks
	 * @return: void
	 * @throws 
	 */
	@Override
	public void batchUpdate(List<RedPacket> waitUpdateRedPacks) {
		redPacketMapper.batchUpdate(waitUpdateRedPacks);
	}
	
	/**
	 * @throws ParseException 
	 * 获取可领取红包集合
	 *
	 * @Title: searchCanGetRedPacket 
	 * @author: wuyicheng
	 * @date: 2017年7月12日下午4:59:55 
	 * @param ruleSet 规则ID
	 * @param sysId 系统ID
	 * @param currentTime 当前系统时间
	 * @param nums 查询数量 
	 * @return
	 * @return: List<RedPacket>
	 * @throws
	 */
	private List<RedPacket> searchCanGetRedPacket(RuleSet ruleSet, Long sysId, String currentTime, Integer nums) throws ParseException {
		RedPacket redPacket = new RedPacket();
		redPacket.setSysId(sysId);
		redPacket.setCreateRuleId(ruleSet.getId());
		redPacket.setStatus(RedPackStatus.INACTIVE);
		redPacket.setIsDraw(RedPacket.IS_DRAW_YES_1);
		
		Pagination page = new Pagination();
		page.setPageSize(nums);
		page.setPageNumber(Pagination.DEFAULT_PAGE_INDEX);
		// 根据规则查询所有红包
		List<RedPacket> canGetRedPackets = redPacketMapper.findListByPage(redPacket, page);
		return canGetRedPackets;
	}
	
	/**
	 * 如果是有效期天数,计算开始结束时间
	 *
	 * @Title: modRedPacktByValidDay 
	 * @author: wuyicheng
	 * @date: 2017年7月12日下午6:17:20 
	 * @param redPacket
	 * @param ruleSet
	 * @param currentTime
	 * @throws ParseException
	 * @return: void
	 * @throws
	 */
	private void modRedPacktByValidDay(RedPacket redPacket, RuleSet ruleSet, String currentTime) throws ParseException {
		if (RuleSet.VALID_DAY_NUM.equals(ruleSet.getValidPeriodType())) {
			int days = ruleSet.getValidDays() == null ? 0 : ruleSet.getValidDays();
			String startTime = currentTime;
			String endTime = DateUtils.getAfterDays(currentTime, days);
			redPacket.setStartTime(startTime);
			redPacket.setEndTime(endTime);
		}
		
	}
	
	/**
	 * 验证会员信息
	 *
	 * @Title: checkMemberInfo 
	 * @author: wuyicheng
	 * @date: 2017年7月12日下午3:17:46 
	 * @param ruleSet 规则
	 * @param sysId 系统ID
	 * @param isMemberLevel 是否按照会员等级派发
	 * @param acceptor 账号集合或者等级集合
	 * @param sendRedPacketResult 发送结果
	 * @throws ParseException
	 * @throws CustomException
	 * @return: List<Map<String, Object>>
	 * @throws
	 */
	private List<Map<String, Object>> checkMemberInfo(RuleSet ruleSet, Long sysId, Short isMemberLevel, String acceptor, SendRedPacketResult sendRedPacketResult)
			throws ParseException, CustomException {
		// 失败手机号
		StringBuffer failPhone = new StringBuffer();
		long successNums = 0L;
		long failNums = 0L;
		long totalNums = 0L;
		
		Map<String, Object> searchMap = new HashMap<>();
		searchMap.put("sysId", sysId);
		List<String> acceptorList = Arrays.asList(acceptor.split(ConstantsUtil.COMMA));
		
		// 去重复
		Map<String, String> phoneAndLevelMap = new HashMap<>();
		for (String string : acceptorList) {
			if (phoneAndLevelMap.get(string) == null) {
				phoneAndLevelMap.put(string, null);
			}
		}
		
		if (SendRedPacketResult.SEND_MEMBER_LEVEL_YES_1 == isMemberLevel) {
			// 按照等级派发
			searchMap.put("memberLevels", acceptorList);
		} else {
			// 按照手机号派发
			searchMap.put("phones", acceptorList);
		}
		
		// 查询全部会员
		List<Map<String, Object>> sendMemberList = memberAccountService.searchSendMember(searchMap);
		
		if (SendRedPacketResult.SEND_MEMBER_LEVEL_YES_1 == isMemberLevel) {
			if (StringUtil.isNotBlank(ruleSet.getLimitMemberLevel())) {
				/*// 规则限制的等级
				List<String> limitLevelList = Arrays.asList(ruleSet.getLimitMemberLevel().split(ConstantsUtil.COMMA));
				
				// 可查询等级
				List<String> canUseList = new ArrayList<>();
				canUseList.addAll(acceptorList);
				canUseList.containsAll(limitLevelList);
				
				// 不可查询等级
				List<String> noCanUseList = new ArrayList<>();
				noCanUseList.addAll(acceptorList);
				noCanUseList.removeAll(limitLevelList);*/
				
				totalNums = sendMemberList.size();
			}
			
		} else {
			totalNums = phoneAndLevelMap.size();
			failNums = totalNums - sendMemberList.size();
		}
		
		sendRedPacketResult.setFailNums(failNums);
		sendRedPacketResult.setSuccessNums(successNums);
		sendRedPacketResult.setFailPhone(failPhone.toString());
		return sendMemberList;
	}
	
	/** 
	 * 统计红包数量
	 * 
	 * @Title: countRedPacket 
	 * @author: wuyicheng
	 * @date: 2017年7月11日下午2:26:32 
	 * @param redPacket
	 * @return
	 * @throws 
	 */
	@Override
	public long countRedPacket(RedPacket redPacket) {
		return redPacketMapper.countRedPacket(redPacket);
	}
	
	/**
	 * 批量插入
	 */
	@Override
	public void insertBatch(String[] list, RedPacket redPacket) {
		redPacketMapper.insertBatch(list, redPacket);
	}
	
	/**
	 * 根据规则id修改红包状态
	 */
	@Override
	public void modityStatusByRuleId(Long ruleId, Long sysId, String status) {
		redPacketMapper.modityStatusByRuleId(ruleId, sysId, status);
	}
	
	/**
	 * 后台红包明细查询
	 */
	@Override
	public PageResult<List<RedPacketDetailVo>> findRedPacketListPage(Long sysId, Integer pageSize, Integer pageNumber, String status, String phoneOrEmail, Long id, String orderNo,
			Long ruleId) {
		RedPacketDetailVo vo = new RedPacketDetailVo();
		vo.setCreateRuleId(ruleId);
		vo.setOrderNo(orderNo);
		vo.setId(id);
		vo.setPhoneOrEmail(phoneOrEmail);
		vo.setStatus(status);
		vo.setSysId(sysId);
		
		Integer redCount = null;
		boolean isPage = false;
		/*if (ruleId == null && StringUtil.isBlank(orderNo) && id == null && StringUtil.isBlank(phoneOrEmail) && StringUtil.isBlank(status)) {
			redCount = redPacketMapper.findRedPacketCount(sysId);
			isPage = true;
			vo.setIsPage(true);
			vo.setOffset(pageNumber);
			vo.setPageDown((pageSize - 1) * pageNumber);
		} else {*/
		PageHelper.startPage(pageNumber, pageSize);
		// }
		List<RedPacketDetailVo> redList = redPacketMapper.findRedPacketListPage(vo);
		PageInfo<RedPacketDetailVo> page = new PageInfo<>(redList);
		PageResult<List<RedPacketDetailVo>> pageObjectVo = new PageResult<>();
		pageObjectVo.setData(redList);
		// if (!isPage) {
		pageObjectVo.setTotal_record(Integer.valueOf(page.getTotal() + ""));
		// } else {
		// pageObjectVo.setTotal_record(redCount);
		// }
		pageObjectVo.setErrorCode(ErrorCode.SUCCESS);
		return pageObjectVo;
	}
	
	@Override
	public RedPacketDetailVo findRedPacketDetailById(Long id, Long sysId) {
		RedPacket red = new RedPacket();
		red.setSysId(sysId);
		red.setId(id);
		Map<String, Object> map = redPacketMapper.findRedPacketDetailById(red);
		return null;
	}
	
	/** 
	 * 导出红包序列号
	 * 
	 * @Title: toExportSerialNumber 
	 * @author: wuyicheng
	 * @date: 2017年7月12日上午11:35:47 
	 * @param ruleSetIds
	 * @param sysId
	 * @param result
	 * @return
	 * @throws 
	 */
	@Override
	public Result<List<Map<String, Object>>> toExportSerialNumber(String ruleSetIds, Long sysId, Result<List<Map<String, Object>>> result) {
		String[] ruleIds = ruleSetIds.split(ConstantsUtil.COMMA);
		List<Map<String, Object>> list = redPacketMapper.findSerialNumber(ruleIds, sysId);
		if (list != null && list.size() > 0) {
			result.setData(list);
		}
		return result;
	}
	
	/**
	 * 送红包-抽奖或用户行为 
	 * @throws ParseException 
	 * @throws CustomException 
	 * 
	 */
	
	public Boolean sendRedPacket(List<Long> ruleIds, Long sysId, Integer num, Long memberId, Long sysUserId, Long winnRecordId, String type, Long sendOrderId)
			throws ParseException, CustomException {
		boolean isSuccess = true;
		if (num > 0) {
			for (Long ruleId : ruleIds) {
				RuleSet rs = ruleSetService.findRuleById(ruleId);
				if (rs == null || !rs.getSysId().equals(sysId) || !RuleType.RED_PACKET.toString().equals(rs.getRuleType())) {
					throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
				}
				
				// 等级
				MemberLevel memberLevel = memberLevelService.findByMemberIdAndSysId(memberId, sysId);
				if (memberLevel != null) {
					boolean isLevelSuccess = ruleSetService.checkLimitMemberLevel(memberLevel, rs);
					if (!isLevelSuccess) {
						log.info("规则限制等级-{}，memberId为{}等级为{}", rs.getLimitMemberLevel(), memberId, memberLevel.getId());
						// log.info("会员行为：规则限制等级-" + rs.getLimitMemberLevel() + "，memberId为" + memberId + "等级为" + memberLevel.getId());
						continue;
					}
				} else {
					// log.info("memberId为" + memberId + "会员等级为空");
					log.info("memberId为{}会员等级为空", memberId);
					throw new CustomException(ErrorCode.RULE_OUT_MEMBER_LEVEL.getCode(), "会员等级不符合要求");
				}
				//
				boolean isOverdue = ruleSetService.isOverdue(rs.getStartDrawTime(), rs.getEndDrawTime(), DateUtils.getCurrentDateTime());
				
				if (isOverdue) {
					log.info("规则Id为{}，已经过了领券时间", rs.getId());
					// log.info("会员行为：规则限制等级-" + rs.getLimitMemberLevel() + "，memberId为" + memberId + "等级为" + memberLevel.getId());
					continue;
				}
				
				// 限领
				RedPacket findRed = new RedPacket();
				findRed.setSysId(sysId);
				findRed.setCreateRuleId(ruleId);
				findRed.setMemberId(memberId);
				long getNum = this.countRedPacket(findRed);
				long limitGetNum = rs.getLimitGetNum() == null ? 0 : rs.getLimitGetNum();
				if (RuleSet.YES.equals(rs.getIsLimitGetNum())) {
					if (limitGetNum - getNum > 0) {
						if (limitGetNum - getNum < num) {
							num = Integer.valueOf((limitGetNum - getNum) + "");
						}
					} else {
						log.info("memberId为{}已经领了{}个红包但是规则id{}限制领取{}个", memberId, getNum, ruleId, limitGetNum);
						// log.info("memberId为" + memberId + "已经领了" + getNum + "个红包但是规则id" + ruleId + "限制领取" + + "个");
						continue;
					}
				}
				String currentTime = DateUtils.getCurrentDateTime();// 获取系统当前时间
				List<RedPacket> redList = searchCanGetRedPacket(rs, sysId, currentTime, num);
				List<RedPacket> waitUpdateRedPacks = new ArrayList<>();
				int length = 0; // 可用红包的个数
				if (redList != null && redList.size() > 0) {
					length = redList.size();
					for (RedPacket rp : redList) {
						// 如果是有效天数，更新开始结束时间
						this.modRedPacktByValidDay(rp, rs, currentTime);
						
						// 构建修改的红包
						this.buildModRedPack(memberId, sysId, sysUserId, currentTime, RedPackStatus.UNUSED, rp);
						rp.setSendOrderId(sendOrderId);
						waitUpdateRedPacks.add(rp);
						
					}
					// 更新红包的使用数量
					if (rs.getUseNum() == null) {
						rs.setUseNum(redList.size());
					} else {
						rs.setUseNum(redList.size() + rs.getUseNum().intValue());
					}
					ruleSetService.updateById(rs);
				}
				
				// 不够的打日志
				
				if (length < num) {
					isSuccess = false;
					// log.info("计划送" + num + "个红包给memberId为" + memberId + "的会员，但是实际数量不够只能送" + redList.size() + "个，ruleId为" + ruleId);
					log.info("计划送{}个红包给memberId为{}的会员，但是实际数量不够只能送{}个，ruleId为{}", num, memberId, redList.size(), ruleId);
					SendNoQuantityLog sendNoQuantityLog = new SendNoQuantityLog();
					sendNoQuantityLog.setActualSendNum(new BigDecimal(redList.size()));
					sendNoQuantityLog.setSrcSendNum(new BigDecimal(num));
					sendNoQuantityLog.setMemberId(memberId);
					sendNoQuantityLog.setSysId(sysId);
					sendNoQuantityLog.setUpdateId(sysUserId);
					sendNoQuantityLog.setCreateId(sysUserId);
					sendNoQuantityLog.setRuleId(ruleId);
					sendNoQuantityLog.setWinnRecordId(winnRecordId);
					sendNoQuantityLog.setType(type);
					sendNoQuantityLog.setRemark("计划送" + num + "个红包给memberId为" + memberId + "的会员，但是实际数量不够只能送" + redList.size() + "个");
					sendNoQuantityLogService.save(sendNoQuantityLog);
				}
				
				// 批量更新红包
				if (waitUpdateRedPacks != null && waitUpdateRedPacks.size() > 0) {
					this.batchUpdate(waitUpdateRedPacks);
				}
				
			}
		} else {
			log.info("赠送的数量为0");
		}
		
		return isSuccess;
		
	}
	
	/**
	 * 查询会员的红包-(状态查询)
	 * @return
	 */
	public PageResult<List<RedPacketShowVo>> searchRedPacketByStatus(Long memberId, Long sysId, String status, Pagination page) {
		// 'UNUSED','USED','EXPIRED'状态:未使用，已使用，已过期
		PageResult<List<RedPacketShowVo>> result = new PageResult<List<RedPacketShowVo>>();
		List<RedPacketShowVo> redPackets = null;
		if (RedPackStatus.USED.toString().equals(status)) {
			redPackets = redPacketMapper.findRedPacketByStatus(memberId, sysId, status, page);
		} else if (RedPackStatus.UNUSED.toString().equals(status)) {
			redPackets = redPacketMapper.findUnusedRedPacket(memberId, sysId, DateUtils.getCurrentDateTime(), page);
		} else if (RedPackStatus.EXPIRED.toString().equals(status)) {
			redPackets = redPacketMapper.findExpiredRedPacket(memberId, sysId, DateUtils.getCurrentDateTime(), page);
		}
		
		if (redPackets != null && redPackets.size() > 0) {
			result.setData(redPackets);
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setTotal_record(page.getTotalRecord());
			result.setMessage("成功查询到红包");
			;
		} else {
			result.setData(null);
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("该会员无状态红包");
			result.setTotal_record(page.getTotalRecord());
			
		}
		return result;
	}
	
	/*public PageResult<List<RedPacketShowVo>> searchUnusedRedPacket(Long memberId, Long sysId, Pagination page) {
		PageResult<List<RedPacketShowVo>> result = new PageResult<List<RedPacketShowVo>>();
		List<RedPacketShowVo> RedPackets = redPacketMapper.findUnusedRedPacket(memberId, sysId, DateUtils.getCurrentDateTime(), page);
		result.setData(RedPackets);
		if (RedPackets != null && RedPackets.size() > 0) {
			result.setTotal_record(page.getTotalRecord());
			result.setMessage("成功查询到红包");
			result.setErrorCode(ErrorCode.SUCCESS);
		} else {
			result.setMessage("没有查询到红包");
			result.setTotal_record(page.getTotalRecord());
			result.setErrorCode(ErrorCode.NOT_FIND);
		}
		return result;
	}
	
	public PageResult<List<RedPacketShowVo>> searchExpiredRedPacket(Long memberId, Long sysId, Pagination page) {
		PageResult<List<RedPacketShowVo>> result = new PageResult<List<RedPacketShowVo>>();
		List<RedPacketShowVo> RedPackets = redPacketMapper.findExpiredRedPacket(memberId, sysId, DateUtils.getCurrentDateTime(), page);
		result.setData(RedPackets);
		if (RedPackets != null && RedPackets.size() > 0) {
			result.setTotal_record(page.getTotalRecord());
			result.setMessage("成功查询到红包");
			result.setErrorCode(ErrorCode.SUCCESS);
		} else {
			result.setMessage("没有查询到红包");
			result.setTotal_record(page.getTotalRecord());
			result.setErrorCode(ErrorCode.NOT_FIND);
		}
		return result;
	}
	*/
	
	/**
	 * 根据订单Id回收红包
	 * @Title: updateOrderSend 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param sendOrderId
	 * @param @param memberId
	 * @param @return
	 * @return int
	 * @throws
	 */
	public void updateOrderSend(Long sendOrderId, Long memberId) {
		redPacketMapper.updateOrderSend(sendOrderId, memberId);
	}
	
	/**
	 * 根据订单Id查询未使用待 回收红包
	 * @Title: sendOrderSend 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param sendOrderId
	 * @param @param memberId
	 * @param @return
	 * @return int
	 * @throws
	 */
	@Override
	public List<RedPacket> selectOrderSend(Long sendOrderId, Long memberId) {
		// TODO Auto-generated method stub
		return redPacketMapper.selectOrderSend(sendOrderId, memberId);
	}
}
